<?php

define ("COLOR", 20);
define ("POINT", 100);
define ("LINE", 10);
define ("WIDTH", 70);
define ("HEIGHT", 28);

// 生成验证码图片
// 分配图片资源, 返回资源句柄
$img = imagecreate(WIDTH, HEIGHT);
// 第一个分配的颜色将作为图片的背景色
$bg = imagecolorallocate($img, 0, 0, 0);
$f_r = mt_rand(140, 255);
$f_g = mt_rand(140, 255);
$f_b = mt_rand(140, 255);
// 用一个浅色的方块覆盖背景色，实现黑色边框的效果
$fg = imagecolorallocate($img, $f_r, $f_g, $f_b);

imagefilledrectangle($img, 1, 1, WIDTH - 2, HEIGHT - 2, $fg);

$color_array = array();
// 整个图片采用 COLORS 种随机颜色
for ($i = 0; $i < COLOR; ++$i) {
	$color_array[] = imagecolorallocate($img, mt_rand(0, 150),
			mt_rand(0, 150), mt_rand(0, 150));
}

// 画随机直线
for ($i = 0; $i != LINE; ++$i) {
	imageline($img, mt_rand(0, WIDTH - 1), mt_rand(0, HEIGHT - 1),
		mt_rand(0, WIDTH - 1), mt_rand(0, HEIGHT - 1),
		$color_array[mt_rand(0, COLOR - 1)]);
}

// 36 个字符
$all_char = "1234567890abcdefghijklmnopqrstuvwxyz";
// 生成四个随机数
$verify_num = array();

for ($i = 0; $i != 4; ++$i) {
	$verify_num[] = $all_char[mt_rand(0, 35)];
	$n = imagecreate(WIDTH / 6, HEIGHT * 0.7);
	$co = imagecolorallocate($n, $f_r, $f_g, $f_b);
	$cf = imagecolorallocate($n, mt_rand(0, 30), mt_rand(0, 30),
			mt_rand(0, 30));
	$angle = mt_rand(-10, 10);
	imagechar($n, 5, 1, 0, $verify_num[$i], $cf);
	$r = imagerotate($n, $angle, $co);
	imagecopyresized($img, $r, 3 + $i * WIDTH / 4, 5, 0, 0,
		WIDTH / 6, HEIGHT * 0.7, WIDTH / 6, HEIGHT * 0.7);
	imagedestroy($n);
}

// 画随机像素点
for ($i = 0; $i != POINT; ++$i) {
	imagesetpixel($img, mt_rand(0, WIDTH - 1), mt_rand(0, HEIGHT - 1),
	$color_array[mt_rand(0, COLOR - 1)]);
}

header("Content-Type: image/png");
imagepng($img);
imagedestroy($img);
session_start();
$_SESSION["verify"] = implode("", $verify_num);

?>